package com.example.custom_bottom_view.CustomBottomView

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.core.view.children
import androidx.navigation.NavController
import com.example.custom_bottom_view.R
import com.google.android.material.internal.ViewUtils.dpToPx
import java.lang.ref.WeakReference

@SuppressLint("ResourceAsColor")
class BottomView(context: Context, attrs:AttributeSet):ViewGroup(context, attrs) {

    private var childWidth = 0
    private var childList:List<TabIconView> = children.toList() as List<TabIconView>

    private var lastSelectedTab = 0
    private var weakNavController : WeakReference<NavController>? = null

    @SuppressLint("RestrictedApi")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val mWidth = MeasureSpec.getSize(widthMeasureSpec)
        val mHeight = dpToPx(context,64).toInt()

        setMeasuredDimension(mWidth,mHeight)
    }

    init {
        setBackgroundColor(R.color.black)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        childWidth = w/4

        childList = children.toList() as List<TabIconView>
        //默认选中第一个
        childList[lastSelectedTab].isSelect(true)
        childList.forEachIndexed { index, tabIconView ->
            tabIconView.index = index
            tabIconView.addListener = { tabIconView, i ->
                selectTabItem(i)
                weakNavController?.get()?.popBackStack()
                weakNavController?.get()?.navigate(tabIconView.id)
            }
        }
    }

    private fun selectTabItem(index: Int) {
        if(index == lastSelectedTab) return
        childList[lastSelectedTab].isSelect(false)
        childList[index].isSelect(true)
        lastSelectedTab = index
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        for (i in 0 until childCount){
            val child = getChildAt(i)
            val left = i*childWidth
            child.layout(left,0,left+childWidth,b-t)
        }
    }

    fun setNavController(navController: NavController){
        weakNavController = WeakReference(navController)
    }

}